package com.woniuxy;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: 马宇航
 * @Description: 消费者
 * @DateTime: 22/12/29/0029 11:08
 * @Component: 成都蜗牛学苑
 **/
public class MQRecvMessage {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //下列4个配置都是默认的配置
        connectionFactory.setHost("localhost");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setPort(5672);//5672是MQ的服务端的端口，15672是可视化页面的端口
        //通过链接工厂创建链接，由链接创建channel信道。
        Channel channel = connectionFactory.newConnection().createChannel();
        channel.queueDeclare("my_queue", false, false, false, null);
        //创建一个消费者去处理消费  匿名消费者
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("消费者获取到了消息："+message);
            }
        };
        channel.basicConsume("my_queue",true,consumer);
        Thread.sleep(3000);
        channel.close();
        connectionFactory.clone();
    }
}
